<template>
  <el-row id="cpts-device">
    <el-row v-if="!isViewShow" class="permission" style="color: black">
      没有权限!
    </el-row>
    <el-card v-else class="box-card">

      <div slot="header" class="clearfix">
        <span>重点能耗设备</span>
        <el-button :disabled="!isViewEdit" style="float: right; padding: 6px 6px;" type="primary" @click="openAddDialog">添加<i class="el-icon-plus el-icon--right"></i></el-button>
      </div>

      <el-table
        :data="tableData"
        stripe
        border
        style="width: 100%;"
        max-height="644">
        <el-table-column
          align="center"
          prop="name"
          label="设备名称">
        </el-table-column>
        <el-table-column
          align="center"
          prop="code"
          label="设备编码">
        </el-table-column>
        <el-table-column
          align="center"
          prop="processElementName"
          label="所属工序单元">
        </el-table-column>
        <el-table-column
          :formatter="statusFormatter"
          align="center"
          prop="status"
          label="设备状态">
        </el-table-column>
        <el-table-column
          align="center"
          prop="model"
          label="设备型号">
        </el-table-column>

        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
            <el-button :disabled="!isViewEdit"
              size="mini"
              @click="handleInfo(scope.$index, scope.row)">编辑</el-button>
            <el-button :disabled="!isViewEdit"
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>

      <!--分页-->
      <div style="text-align: center;margin-top: 10px;">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="paginationCount"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="currentChange">
        </el-pagination>
      </div>

    </el-card>

    <!--弹窗-->
    <el-dialog title="添加/编辑" :visible.sync="editDialogShow">
      <el-form :model="ruleForm" ref="ruleForm" :rules="rules"  label-width="100px">

        <el-row>
          <el-col :span="8">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备编码" prop="code">
              <el-input  v-model="ruleForm.code"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="ruleForm.status"  placeholder="请选择状态">
                <el-option
                  v-for="item in fields"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="所属工序" prop="">
              <el-select v-model="processValue"  placeholder="请选择工序" @change="onProcessSelect">
                <el-option
                  v-for="item in processOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属工序单元" prop="processElementId">
              <el-select v-model="ruleForm.processElementId"  placeholder="请选择工序单元">
                <el-option
                  v-for="item in processUnitOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备型号" prop="model">
              <el-input v-model="ruleForm.model"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row class="cp-submit-layout">
          <el-button @click="submitAdd('ruleForm')" type="primary" :loading="false">提交</el-button>
        </el-row>

      </el-form>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="warnDialogShow"
      width="30%">
      <span>该数据正在被使用,删除会影响数据的正常上报。确定需要删除么?</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="warnDialogShow = false">取 消</el-button>
    <el-button type="primary" @click="handlerDeleteForWarn">确 定</el-button>
  </span>
    </el-dialog>
  </el-row>
</template>

<script>
  export default {
    name: "device",
    props: ['options'],
    data(){
      return {
        isViewShow: false,
        isViewEdit: false,
        paginationCount: 11,
        currentPage: 1,
        pageSize: 11,
        editDialogShow: false,
        warnDialogShow:false,
        deleteId: '',
        processValue: '',
        deleteStatus: 0,
        tableData: [],
        optionDatas: [],
        processOptions:[],
        processUnitOptions:[],
        fields:[{value: 0,label: '未使用'},{value: 1,label: '正常使用'}],
        ruleForm:{
          id: "",
          processElementId: "",
          name: "",
          code: "",
          status: '',
          model: ""
        },
        rules: {
          name:[
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          code:[
            { required: true, message: '请输入', trigger: 'blur' },
          ],
        },
      }
    },
    watch:{
     /* options:{
        handler(val,oldval){
          let arry = []
          for(let i = 0;i< val.length;++i){
            let obj = {}
            obj.label = val[i].name
            obj.value = val[i].id
            let arry2 = []
            for(let j = 0;j < val[i].processElements.length;++j){
              let obj = {}
              obj.label = val[i].processElements[j].name
              obj.value = val[i].processElements[j].id
              arry2.push(obj)
            }
            obj.child = arry2
            arry.push(obj)
          }
          this.optionDatas = arry
          this.initProcessOptionDatas()
        },
        deep:true
      }*/
    },
    mounted(){
      let obj = this.validateGlobal.getPermission(19)
      this.isViewShow = obj.isViewShow
      this.isViewEdit = obj.isViewEdit

     this.askTreeDatas()

      this.askListsData()
    },
    methods:{
      initProcessOptionDatas(){
        if (!this.validateGlobal.isEmpty(this.optionDatas)) {
          let arry = []
          for(let i = 0;i<this.optionDatas.length;++i){
            let obj = {}
            obj.label = this.optionDatas[i].label
            obj.value = this.optionDatas[i].value
            arry.push(obj)
          }
          this.processOptions = arry
        }
      },
      onProcessSelect(key){
        if (!this.validateGlobal.isEmpty(this.optionDatas)) {
          for(let i = 0;i<this.optionDatas.length;++i){
            if (key === this.optionDatas[i].value) {
              this.processUnitOptions = this.optionDatas[i].child
            }
          }
          this.processValue = key
        }
      },
      statusFormatter(row, column) {
        let status = row.status;
        if(status === 0){
          return '未使用'
        } else {
          return '正常'
        }
      },
      openAddDialog(){
        if (!this.editDialogShow) {
          this.editDialogShow = true
        }
        this.resetForm()
      },
      resetForm: function(){   // 表单重置
        /*if (this.$refs['ruleForm']!==undefined) {
          this.$refs['ruleForm'].resetFields();
        }*/
        this.ruleForm.status = ''
        this.ruleForm.id = ''
        this.ruleForm.processElementId = ''
        this.ruleForm.name = ''
        this.ruleForm.code = ''
        this.ruleForm.model = ''
        this.processValue = ''
      },
      handleDelete(index,item){
        this.deleteId = item.id
        if (item.isBinding === 0){
          this.deleteStatus = 0
          this.deleteItem()
        }else{
          this.deleteStatus = 1
          if (!this.warnDialogShow) {
            this.warnDialogShow = true
          }
        }
      },
      handlerDeleteForWarn(){
        let _that = this
        this.deleteItem()
        this.warnDialogShow = false
      },
      handleInfo(index, row) {
        console.log(index, row);
        // let obj = this.validateGlobal.cloneObject(row)
        this.onProcessSelect(row.processId)
        this.ruleForm.status = row.status
        this.ruleForm.id = row.id
        // this.processValue = row.processId
        this.ruleForm.processElementId = row.processElementId
        this.ruleForm.name = row.name
        this.ruleForm.code = row.code
        this.ruleForm.model = row.model
        if (!this.editDialogShow) {
          this.editDialogShow = true
        }
      },
      currentChange(currentPage){
        this.currentPage = currentPage;
        this.askListsData()
      },
      submitAdd: function (formName) {
        let _that = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            _that.postNewDatas()
          } else {
            _that.$message('输入有误!');
            return false;
          }
        });
      },
      askTreeDatas: function(){
        let _that = this
        let userId = sessionStorage.getItem("userId")
        let url = _that.ports.procedureManage.process.all
        let askData = {
          userId: userId,
        }
        this.http.get(url,askData, res => {
          console.log("treeDatas",res)
          if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
            let arry = []
            for(let i = 0;i< res.data.length;++i){
              let obj = {}
              obj.label = res.data[i].name
              obj.value = res.data[i].id
              let arry2 = []
              for(let j = 0;j < res.data[i].processElements.length;++j){
                let obj = {}
                obj.label = res.data[i].processElements[j].name
                obj.value = res.data[i].processElements[j].id
                arry2.push(obj)
              }
              obj.child = arry2
              arry.push(obj)
            }
            _that.optionDatas = arry
            _that.initProcessOptionDatas()
          }else{
            _that.$message('数据获取失败!');
          }
        })
      },
      askListsData: function () {
        let _that = this
        let userId = sessionStorage.getItem("userId")
        let url = _that.ports.procedureManage.device.lists
        let askData = {
          userId: userId,
          current: _that.currentPage,
          size: _that.pageSize
        }
        this.http.get(url,askData, res => {
          console.log("deviceLists",res)
          if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
            _that.tableData = res.data.records
            _that.paginationCount = res.data.total
          }else{
            _that.$message('列表获取失败!');
          }
        })
      },
      postNewDatas: function () {
        let _that = this
        let userId = sessionStorage.getItem("userId")
        let url = _that.ports.procedureManage.device.add + '?userId=' + userId
        let askData = this.ruleForm
        this.http.post(url,askData, res => {
          if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
            _that.$message('添加成功!');
            _that.editDialogShow = false
            _that.askListsData()
            _that.$emit('func')
          }else{
            _that.$message('新增失败!');
          }
        })
      },
      deleteItem:function () {
        let _that = this
        let userId = sessionStorage.getItem("userId")
        let url = _that.ports.procedureManage.device.delete
        let askData = {
          userId: userId,
          isBinding: _that.deleteStatus,
          id:_that.deleteId,
        }
        this.http.get(url,askData, res => {
          if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
            _that.$message('删除成功!');
            _that.askListsData()
            _that.$emit('func')
          }else{
            _that.$message('删除失败!');
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  #cpts-device{
    .el-card{
      margin: 10px 10px 0px 0px;
      height: 780px;
    }

    .cp-submit-layout{
      display: flex;
      justify-content: center;
    }
  }
</style>
